//
//  BiaoListViewController.swift
//  jiaoyi
//
//  Created by wjk on 2018/8/15.
//  Copyright © 2018年 wjk. All rights reserved.
//

import UIKit
import MJRefresh
import SwiftyJSON

class BiaoListViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {

    var id:String!
    var page:Int = 1;
    var type:Int = 0;  //默认是竞价
    var datas:[JSON] = [JSON]()
    
    var types:[JSON] = [JSON]()
    
    var variety_id:String = ""
    
    @IBOutlet weak var typeTableView: UITableView!
    
    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var bgView: UIView!
    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(R.nib.biaoListTableViewCell(), forCellReuseIdentifier: BiaoListTableViewCell.cellIdenti())
        tableView.rowHeight = UITableViewAutomaticDimension
        self.title = "标的安排"
        
        let header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.page = 1;
            self?.loadData()
        })
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "fliter_icon"), style: .plain, target: self, action: #selector(self.openMenu(_:)));
        tableView.mj_header = header
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[weak self] in
            self?.loadData()
        })
        tableView.mj_header.beginRefreshing()
        
        let textFieldInsideSearchBar = searchBar.value(forKey: "searchField")as? UITextField
        
        textFieldInsideSearchBar?.textColor = UIColor.gray
        
        let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.value(forKey: "placeholderLabel")as? UILabel
        
        textFieldInsideSearchBarLabel?.textColor = UIColor.gray
        // Do any additional setup after loading the view.
    }
    
    @objc func openMenu(_ sender: UIBarButtonItem) {
        
        self.bgView.isHidden = !self.bgView.isHidden
    }
    
    func loadData() -> Void {
        NetWorkRequest(.fairtarget(id: id,page:"\(page)", alig: self.searchBar.text, type: self.variety_id)) { (res) -> (Void) in
            
            if res["code"] as! String == "000000" {
                let jd = jsonFormater(data: res["data"] as Any)
                
                
                let arr = jd["targets"].dictionaryValue["data"]?.arrayValue
                
                
                self.types = (jd["options"].dictionaryValue["varieties"]?.arrayValue)!
                
                self.typeTableView.reloadData()
                
                if self.page <= 1 {
                    self.datas.removeAll()
                }
                arr?.forEach({ (js) in
                    self.datas.append(js)
                })
                self.page += 1
                
                if arr?.count ?? 0 <= AppConstants.pre_count {
                    self.tableView.mj_footer.isHidden = true
                }else {
                    self.tableView.mj_footer.isHidden = false
                }
                self.tableView.reloadData()
            }
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
        }
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        self.page = 1;
        self.loadData()
        self.view.endEditing(true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == self.typeTableView {
            return self.types.count
        }
        return self.datas.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if tableView == self.typeTableView {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cells")!
            cell.textLabel?.text = self.types[indexPath.row]["name"].stringValue
            return cell
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: BiaoListTableViewCell.cellIdenti()) as! BiaoListTableViewCell
        cell.selectionStyle = .none
        let dic = self.datas[indexPath.row]
        cell.labelBiaoNo.text = "标的号：\(dic["alias"].stringValue)"
        cell.labelAddress.text = dic["grain_origin"].stringValue
        cell.labelStatus.text = dic["status_show"].stringValue
        cell.labelCate.text = dic["variety_show"].stringValue
        cell.labelLevel.text = dic["grade_show"].stringValue
        cell.labelXing.text = dic["grain_type_show"].stringValue
        
        if type != 0 {
            cell.labelTitle.text = "标价："
            cell.label2.text = ""
            cell.label3.text = ""
        }
        
        cell.labelNum.attributedText = StyledTextBuilder(text: "")
            .save()
            .add(text: "\(dic["num"].stringValue)", traits: [.traitBold], attributes: [NSAttributedStringKey.foregroundColor:UIColor.red, NSAttributedStringKey.font:UIFont.systemFont(ofSize: 16)])
            .restore()
            .add(text: " \(dic["num_unit"].stringValue)", traits: [.traitBold], attributes: [NSAttributedStringKey.foregroundColor:UIColor.black, NSAttributedStringKey.font:UIFont.systemFont(ofSize: 14)])
            .restore()
            .build()
            .render(contentSizeCategory: .large)
        cell.labelJia.attributedText = StyledTextBuilder(text: "")
            .save()
            .add(text: "\(dic["base_price_show"].stringValue)", traits: [.traitBold], attributes: [NSAttributedStringKey.foregroundColor:UIColor.red, NSAttributedStringKey.font:UIFont.systemFont(ofSize: 16)])
            .restore()
            .add(text: " \(dic["price_unit"].stringValue)", traits: [.traitBold], attributes: [NSAttributedStringKey.foregroundColor:UIColor.black, NSAttributedStringKey.font:UIFont.systemFont(ofSize: 14)])
            .restore()
            .build()
            .render(contentSizeCategory: .large)
        cell.labelJie.text = dic["section_number"].stringValue
        if dic["open_at"].stringValue.isEmpty {
            cell.labelDate.text = "交易中"
        }else {
            cell.labelDate.text = dic["open_at"].stringValue
        }
        
        if (UIApplication.shared.delegate as! AppDelegate).isBuy == 1 {
            cell.imgIcon.image = UIImage.init(named: "买")
        }else {            
            cell.imgIcon.image = UIImage.init(named: "icon_biao_mai")
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if tableView == self.typeTableView {
            self.page = 1
            self.variety_id = self.types[indexPath.row]["id"].stringValue
            
            self.bgView.isHidden = true
            self.loadData()
            
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

    @IBAction func hidden(_ sender: UITapGestureRecognizer) {
        self.bgView.isHidden = true
    }
}
